package com.monas.client.util;

import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;

import com.monas.client.export.Renderer;

/**
 * Class untuk menjalankan progress monitor.
 * 
 * @author 'Eko Wahyudi'
 * 
 */
public class ProgressExporting {

	/**
	 * File output stream untuk menulis ke file.
	 */
	private final FileOutputStream fos;

	/**
	 * Table excel untuk export file.
	 */
	private final Renderer table;

	/**
	 * Shell untuk menjalankan {@link ProgressMonitorDialog}.
	 */
	private final Shell parent;

	/**
	 * Buat objek untuk melakukan progress exporting.
	 * 
	 * @param parent
	 *            shell utama
	 * @param table
	 *            table excel
	 * @param fos
	 *            file output stream
	 */
	public ProgressExporting(Shell parent, Renderer table, FileOutputStream fos) {
		this.parent = parent;
		this.table = table;
		this.fos = fos;
	}

	/**
	 * Menjalankan proses export ke file excel.
	 * 
	 * @return {@link FileOutputStream}
	 * @throws InvocationTargetException
	 *             error target
	 * @throws InterruptedException
	 *             error interupsi
	 */
	public FileOutputStream run() throws InvocationTargetException,
			InterruptedException {
		ProgressMonitorDialog dialog = new ProgressMonitorDialog(parent);
		dialog.run(true, false, new Exporting());
		return fos;
	}

	/**
	 * Class progress untuk eksport file.
	 * 
	 * @author 'EkoWahyudi'
	 * 
	 */
	private class Exporting implements IRunnableWithProgress {

		@Override
		public void run(IProgressMonitor monitor)
				throws InvocationTargetException, InterruptedException {
			/**
			 * Monitor dimulai.
			 */
			String task = "Exporting Table into Documents";
			monitor.beginTask(task, 2 + 1);
			try {
				monitor.setTaskName("Rendering Table...");
				table.render();
				monitor.worked(1);

				monitor.setTaskName("Writing into File...");
				table.writeTo(fos);
				monitor.worked(1);
			} catch (Exception e) {
//				String message = "Fail export to excel";
//				throw new InvocationTargetException(e, message);
				e.printStackTrace();
			} finally {

				/**
				 * Monitor selesai.
				 */
				monitor.done();
			}
		}

	}

}
